package com.yy.module.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yy.base.common.action.BaseCtrl;
import com.yy.base.log.Logger;
import com.yy.base.log.LoggerFactory;
import com.yy.base.page.Message;
import com.yy.base.util.ObjectUtil;
import com.yy.base.util.StringUtil;
import com.yy.module.entity.Field;
import com.yy.module.entity.Table;
import com.yy.module.service.TableService;

@Controller
@SuppressWarnings("unchecked")
@RequestMapping(value = "/tableAction")
public class TableAction extends BaseCtrl {
	private Logger log = LoggerFactory.getLogger(TableAction.class);
	private static final long serialVersionUID = 1L;
	@Autowired
	private TableService service;
	
	/**
	 * 查询所有表
	 */
	@ResponseBody
	@RequestMapping(value="/getFieldList.html")
	public Message getFieldList(HttpServletRequest request) {
		Field field = ObjectUtil.mapToEntity(Field.class, this.getParameterMap(request));
		Message message = new Message();
		try {
			String tableName = request.getParameter("tableName");
			if (tableName != null && !"".equals(tableName)) {
				field = new Field();
			} else if (field == null || StringUtil.isEmpty(field.getTableId())) {
				message.setPageList(new ArrayList());
				return message;
			}
			message.setPageList(service.getFieldList(field, tableName));
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("查询异常！");
		}
		return message;
	}
	/**
	 * 根据字段ID，查询字段信息
	 */
	@ResponseBody
	@RequestMapping(value="/getFieldInfoById.html")
	public Message getFieldInfoById(HttpServletRequest request) {
		Message message = new Message();
		message.formartData(service.getFieldInfoById(request.getParameter("id")));
		return message;
	}
	/**
	 * 查询所有表
	 */
	@ResponseBody
	@RequestMapping(value="/getTableList.html")
	public Message getTableList(HttpServletRequest request) {
		Table table = ObjectUtil.mapToEntity(Table.class, this.getParameterMap(request));
		Message message = new Message();
		try {
			if (table == null) {
				table = new Table();
			}
			message.setPageList(service.getTableList(table));
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("查询异常！");
		}
		return message;
	}
	/**
	 * 查询所有表类型
	 */
	@ResponseBody
	@RequestMapping(value="/getTableType.html")
	public Message getTableType() {
		Message message = new Message();
		try {
			message.formartData(service.getTableType());
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("查询异常！");
		}
		return message;
	}
	/**
	 * 根据表ID，查表信息
	 */
	@ResponseBody
	@RequestMapping(value="/getTableInfoById.html")
	public Message getTableInfoById(HttpServletRequest request) {
		Message message = new Message();
		Table table = service.getTableInfoById(request.getParameter("id"));
		message.formartData(table);
		return message;
	}
	
	/**
	 * 保存表信息
	 */
	@ResponseBody
	@RequestMapping(value="/saveTable.html")
	public Message saveTable(HttpServletRequest request) {
		Table table = ObjectUtil.mapToEntity(Table.class, this.getParameterMap(request));
		Message message = new Message();
		try {
			if (StringUtil.isNotEmpty(table.getId())) {
				service.update(table, "t_table");
			} else {
				service.save(table, "t_table");
			}
			message.setOkMessage("保存表信息成功！");
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("保存表信息异常！");
		}
		return message;
	}
	/**
	 * 加载表字段信息
	 */
	@ResponseBody
	@RequestMapping(value="/loadTableField.html")
	public Message loadTableField(HttpServletRequest request) {
		Field field = ObjectUtil.mapToEntity(Field.class, this.getParameterMap(request));
		Message message = new Message();
		try {
			String tableId = request.getParameter("tableId");
			if (StringUtil.isNotEmpty(tableId)) {
				Table table = service.getTableInfoById(tableId);
				if (StringUtil.isEmpty(table.getName())) {
					message.setErrorMessage("表信息中表名为空！");
					return message;
				}
				//自动加载表字段
				List<Map> list = service.getFields(table.getName());
				field = new Field();
				field.setTableId(table.getId());
				
				Field f = null;
				Field oldField = null;
				for (Map map : list) {
					field.setName((String)map.get("name"));
					field.setFixed((Integer)map.get("fixed"));
					field.setIsNotNull((Integer)map.get("isNotNull") == 1 ? 0 : 1);
					field.setLength((Integer)map.get("length"));
					field.setTypeId(getColumnType((String)map.get("type"), field.getFixed()));
					//field.setIsOnly((Boolean)map.get("signed") ? 1 : 0);
					
					f = service.getFieldByName(field.getName());
					if (f != null) {
						field.setText(f.getText());
						field.setIsId(f.getIsId());
					} else {
						field.setText((String)map.get("text"));
					}
					oldField = service.getFieldInfoById(field.getName(), tableId);
					if (oldField == null) {
						field.setId(StringUtil.getUUID());
						service.save(field, "t_field");
					} else {
						oldField.setTypeId(field.getTypeId());
						//如果当前字段名、字段名称相同，更新其他表更改过的字段名
						if (oldField.getName().equals(oldField.getText())) {
							oldField.setText(field.getText());
						}
						service.update(oldField);
					}
				}
				message.setOkMessage("字段加载成功！");
			} else {
				message.setErrorMessage("传入表格ID为空！");
			}
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("加载字段内容失败！");
		}
		return message;
	}
	
	/**
	 * 根据数据中型号生成类型
	 */
	private String getColumnType(String type, int fixed) {
		if ("INT".equals(type.toUpperCase()) || "LONG".equals(type.toUpperCase())) {
			return Field.INT;
		}
		if ("FLOAT".equals(type.toUpperCase()) || "DOUBLE".equals(type.toUpperCase())) {
			return Field.FLOAT;
		}
		if ("NUMBER".equals(type.toUpperCase())) {
			if (fixed > 0) {
				return Field.FLOAT;
			}
			return Field.INT;
		}
		if ("DATE".equals(type.toUpperCase()) || "DATETIME".equals(type.toUpperCase())) {
			return Field.DATE;
		}
		return Field.STRING;
	}
	
	/**
	 * 保存表信息
	 */
	@ResponseBody
	@RequestMapping(value="/saveField.html")
	public Message saveField(HttpServletRequest request) {
		Field field = ObjectUtil.mapToEntity(Field.class, this.getParameterMap(request));
		Message message = new Message();
		try {
			if (StringUtil.isNotEmpty(field.getId())) {
				service.update(field, "t_field");
			} else {
				service.save(field);
			}
			message.setOkMessage("保存字段信息成功！");
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("保存字段信息异常！");
		}
		return message;
	}
	/**
	 * 删除字段
	 */
	@ResponseBody
	@RequestMapping(value="/deleteField.html")
	public Message deleteField(HttpServletRequest request) {
		String id = request.getParameter("id");
		Message message = new Message();
		try {
			if (StringUtil.isNotEmpty(id)) {
				service.executeSql("delete t_Field where id = ?", id);
			}
			message.setOkMessage("删除字段信息成功！");
		} catch (Exception e) {
			log.error(e);
			message.setErrorMessage("删除字段信息异常！");
		}
		return message;
	}
}